/**
 * Copyright (c) 2017-2020 四川智慧云天 All rights reserved.
 *
 * https://www.sczhyt.cn
 *
 * 版权所有，侵权必究！
 */

package cn.sczhyt.common.utils;

import cn.sczhyt.common.exception.RRException;
import cn.sczhyt.modules.sys.dao.SysRoleDao;
import cn.sczhyt.modules.sys.dao.SysUserRoleDao;
import cn.sczhyt.modules.sys.entity.SysRoleEntity;
import cn.sczhyt.modules.sys.entity.SysUserEntity;
import cn.sczhyt.modules.sys.entity.SysUserRoleEntity;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Shiro工具类
 *
 * @author Mark sunlightcs@gmail.com
 */
public class ShiroUtils {


	@Autowired
	static SysUserRoleDao userRoleDao;
	@Autowired
	static SysRoleDao roleDao;

	public static Session getSession() {
		return SecurityUtils.getSubject().getSession();
	}

	public static Subject getSubject() {
		return SecurityUtils.getSubject();
	}

	public static SysUserEntity getUserEntity() {
		return (SysUserEntity)SecurityUtils.getSubject().getPrincipal();
	}

	public static String getUserId() {
		return getUserEntity().getUserId();

	}

	public static String getUsername() {
		return getUserEntity().getUsername();
	}

	public static SysUserRoleEntity getUserRole() {
		return userRoleDao.selectByUserId(getUserId());
	}

	public static String getRoleId() {
		return getUserRole().getRoleId();
	}

	public static SysRoleEntity getRole(){
		return roleDao.selectById(getRoleId());
	}
	public static String getRoleName(){
		return getRole().getRoleName();
	}


	public static void setSessionAttribute(Object key, Object value) {
		getSession().setAttribute(key, value);
	}

	public static Object getSessionAttribute(Object key) {
		return getSession().getAttribute(key);
	}

	public static boolean isLogin() {
		return SecurityUtils.getSubject().getPrincipal() != null;
	}

	public static String getKaptcha(String key) {
		Object kaptcha = getSessionAttribute(key);
		if(kaptcha == null){
			throw new RRException("验证码已失效");
		}
		getSession().removeAttribute(key);
		return kaptcha.toString();
	}

}
